﻿using System;
using System.Linq;
using System.Web.Mvc;

namespace Kooboo.Web.Areas.Commerce.Controllers
{
    using System.Collections.Generic;
    using Kooboo.Commerce;
    using Kooboo.Commerce.AddIn;
    using Kooboo.IoC;
    using Kooboo.Web.Mvc;
    using Kooboo.Commerce.Contexts.ProductTypes;


    [Authorize(Roles = "Administrator")]
    public class ProductTypeController : ManagementController
    {

        public ActionResult Index()
        {
            
            ViewData["edit-action"] = this.Url.Action<ProductTypeController>(i => i.Edit(-1));
            ViewData["delete-action"] = this.Url.Action<ProductTypeController>(i => i.Delete(null));
         

            return View(this.Actor.QueryProductTypes().AsEnumerable());
        }

        #region Create
        public ActionResult Create()
        {
            var item = ObjectContainer.CreateInstance<IProductType>();

            SerializeWebControls();
            SerializeValidators();

            ViewData["CustomFields"] = "[]";
            ViewData["Variations"] = "[]";
            ViewData["list-action"] = this.Url.Action<ProductTypeController>(i => i.Index());

            return View(item);
        }

        [HttpPost]
        public ActionResult Create(IProductType productType)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    this.Actor.Post(productType);

                    return Json(true);
                }
                catch (Exception ex)
                {
                    return Json(new { Message = ex.Message });
                }
            }
            else
            {
                return Json(new { Error = ModelState.GetErrorMessages() });
            }
        } 
        #endregion

        #region Edit
        public ActionResult Edit(int id)
        {
            var productType = this.Actor
                .QueryProductTypes()
                .Where(i => i.Id == id)
                .FirstOrDefault();

            if (productType == null)
                return HttpNotFound();

            SerializeWebControls();

            SerializeValidators();


            ViewData["CustomFields"] = productType.CustomFields
                .OrderBy(i => i.Sequence)
                .Select(i => new
                {
                    i.Id,
                    i.Name,
                    i.DataFormat,
                    i.DefaultValues,
                    Selections = string.Join(Environment.NewLine, i.Selections.ToArray()),
                    i.Sequence,
                    WebControlName = i.WebControl.Name,
                    Rules = i.ValidationRules.Select(rule => new
                    {
                        rule.Id,
                        ValidatorName = rule.Validator.Name,
                        Parameters = rule.Parameters,
                        rule.ErrorMessage
                    }).ToList(),
                })
                .ToList()
                .SerializeToJson();

            ViewData["Variations"] = productType.Variations
                .Select(i => new
                {
                    i.Id,
                    i.Name,
                    i.DataFormat,
                    i.DefaultValues,
                    Selections = string.Join(Environment.NewLine, i.Selections.ToArray()),
                    i.Sequence,
                    WebControlName = i.WebControl.Name,
                    Rules = i.ValidationRules.Select(rule => new
                    {
                        rule.Id,
                        ValidatorName = rule.Validator.Name,
                        Parameters = rule.Parameters,
                        rule.ErrorMessage
                    }).ToList(),
                })
                .ToList()
                .SerializeToJson();

            ViewData["list-action"] = this.Url.Action<ProductTypeController>(i => i.Index());


            return View(productType);
        }

        [HttpPost]
        public ActionResult Edit(IProductType productType)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    
                    this.Actor.Put(productType);

                    return Json(true);
                }
                catch (Exception ex)
                {
                    return Json(ex.Message);
                }
            }
            else
            {
                return Json(ModelState.GetErrorMessages());
            }

        } 
        #endregion

        #region Delete

        [HttpPost]
        public ActionResult Delete(IProductType productType)
        {
         
            try
            {
                this.Actor.Delete(productType);

                return Json(true);
            }
            catch (Exception ex)
            {
                return Json(ex.Message);
            }

        }


        [HttpPost]
        public ActionResult BatchDelete(int[] selected)
        {

            try
            {
                var items = new List<IProductType>();

                
                foreach (var i in selected)
                {
                    var item = ObjectContainer.CreateInstance<IProductType>();
                    item.Id = i;
                    items.Add(item);
                }


                this.Actor.Delete(items);

                return Json(true);
            }
            catch (Exception ex)
            {
                return Json(ex.Message);
            }

        }

        #endregion

        #region Enable/Disable
        [HttpPost]
        public JsonResult Enable(IProductType model)
        {
            model.Enable();
            return Json(true);
        }

        [HttpPost]
        public JsonResult Disable(IProductType model)
        {
            model.Disable();
            return Json(true);
        } 
        #endregion
        
        private void SerializeWebControls()
        {
            ViewData["WebControls"] = ObjectContainer.CreateInstances<IWebControl>()
                .Select(i => new
                {
                    Name = i.Name,
                    DataFormats = i.DataFormats.Select(n => new
                    { 
                        Name = n.ToString(),
                        Value = (int)n
                    }).ToArray()
                })
                .ToList()
                .SerializeToJson();
        }

        private void SerializeValidators()
        {
            ViewData["Validators"] = ObjectContainer.CreateInstances<IValidator>().OrderBy(i => i.Name)
                .Select(i => new
                {
                    i.Name,
                    Parameters = i.GetParameters().Select(n => new
                    {
                        n.Name,
                        n.Example,
                    })
                })
                .ToList()
                .SerializeToJson();
        }
    }
}
